import { Body, Get, UploadedFile, UseInterceptors } from '@nestjs/common';
import { Session, Post, Req, Controller, UseGuards } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { AuthGuard } from '@nestjs/passport';
import { FileInterceptor } from '@nestjs/platform-express';
import {
  ApiBearerAuth,
  ApiOperation,
  ApiProperty,
  ApiTags,
} from '@nestjs/swagger';
import { LocalAuthGuard } from './localauth.guard';
const svgCaptcha = require('svg-captcha');

class UserDto {
  @ApiProperty({ description: '待校验的用户名', example: 'admin' })
  username: string;

  @ApiProperty({ description: '待校验的密码', example: '123456' })
  password: string;
}

@ApiTags('登录校验')
@Controller('/')
export class AdminController {
  constructor(private readonly jwtService: JwtService) {}

  @ApiOperation({ summary: '登录校验' })
  @UseGuards(LocalAuthGuard)
  @Post('login')
  login(@Body() user: UserDto, @Req() request: any) {
    const payload = { _id: request.user._id };
    return {
      token: this.jwtService.sign(payload),
    };
  }

  @ApiOperation({ summary: '文件上传' })
  @UseGuards(AuthGuard('jwt'))
  @ApiBearerAuth()
  @Post('upload')
  @UseInterceptors(FileInterceptor('file'))
  upload(@UploadedFile() file: any) {
    return file;
  }

  @ApiOperation({ summary: '验证码' })
  @Get('verifcode')
  verifCode(@Session() session: any) {
    const captcha = svgCaptcha.create();
    session.code = captcha.text;
    return { image: captcha.data };
  }
}
